import 'package:dio/dio.dart' as dio;
import 'package:file_picker/file_picker.dart' as picker;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';
import 'package:management/const/init.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/project/request/SubmitProjectRequestParams.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/toast.dart';
import 'package:management/generated/assets.dart';

import 'state.dart';

class CreateProjectScreeLogic extends GetxController {
  final CreateProjectScreeState state = CreateProjectScreeState();

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  void selectStatus() {
    Get.bottomSheet(
        Wrap(
            children: List<Widget>.generate(5, (index) {
          return Container(
            padding: const EdgeInsets.symmetric(vertical: 2),
            width: double.infinity,
            height: 60,
            child: TextButton(
              onPressed: () {
                if (index == 4) {
                  Get.back();
                  return;
                }
                state.projectStatus.value = index + 1;
                state.statusController.text =
                    state.listClassification[state.projectStatus.value]!;
                Get.back();
              },
              style: Theme.of(Get.context!).textButtonTheme.style,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    index == 4
                        ? MyText.cancel
                        : state.listClassification[index + 1]!,
                    style: Theme.of(Get.context!).textTheme.bodyLarge?.copyWith(
                        color: index == 4
                            ? MyColor.error
                            : MyColor.grayScale[500]),
                  ),
                ],
              ),
            ),
          );
        })),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void selectCharge() {
    Get.bottomSheet(
        Flexible(
          child: ListView.builder(
            itemBuilder: (context, index) {
              return SizedBox(
                height: 50,
                child: ListTile(
                  leading: ClipOval(
                    child: FadeInImage(
                      image: NetworkImage(state.listNumbers[index].avatar ??
                          GlobalInit.headImage),
                      height: 45.w,
                      width: 45.h,
                      fit: BoxFit.fill,
                      placeholderFit: BoxFit.scaleDown,
                      placeholder: const AssetImage(Assets.iconAvator),
                    ),
                  ),
                  title: Text(
                    state.listNumbers[index].nickname ?? MyText.loading,
                    style: Theme.of(Get.context!).textTheme.titleSmall,
                  ),
                  subtitle: Text(
                    state.listNumbers[index].realName ?? MyText.loading,
                    style: Theme.of(Get.context!).textTheme.bodyMedium,
                  ),
                  onTap: () {
                    state.chargeUrl.value =
                        state.listNumbers[index].avatar ?? GlobalInit.headImage;
                    state.chargeId.value =
                        state.listNumbers[index].id.toString();
                    Get.back();
                  },
                ),
              );
            },
            itemCount: state.listNumbers.length,
          ),
        ),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void showMultipleSelectionInterface() {
    Get.bottomSheet(StatefulBuilder(builder:
            (BuildContext context, void Function(void Function()) setState) {
      return SizedBox(
        height: 500,
        child: Column(
          children: [
            SizedBox(
              height: 400,
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return SizedBox(
                    height: 50,
                    child: ListTile(
                      leading: ClipOval(
                        child: FadeInImage(
                          image: NetworkImage(state.listNumbers[index].avatar ??
                              GlobalInit.headImage),
                          height: 45.w,
                          width: 45.h,
                          fit: BoxFit.fill,
                          placeholderFit: BoxFit.scaleDown,
                          placeholder: const AssetImage(Assets.iconAvator),
                        ),
                      ),
                      title: Text(
                        state.listNumbers[index].nickname ?? MyText.defaultName,
                        style: Theme.of(Get.context!).textTheme.titleSmall,
                      ),
                      subtitle: Text(
                        state.listNumbers[index].realName ?? MyText.defaultName,
                        style: Theme.of(Get.context!).textTheme.bodyMedium,
                      ),
                      trailing: Checkbox(
                          value: state.mapSelect[state.listNumbers[index]]!,
                          onChanged: (value) {
                            setState(() {
                              var ss =
                                  state.mapSelect[state.listNumbers[index]] ??
                                      false;
                              state.mapSelect[state.listNumbers[index]] = !ss;
                            });
                          }),
                    ),
                  );
                },
                itemCount: state.listNumbers.length,
              ),
            ),
            TextButton(
                onPressed: () {
                  state.listSelectNumbers.clear();
                  state.mapSelect.forEach((key, value) {
                    state.listSelectNumbers.addIf(value, key);
                    state.listSelectNumbers.refresh();
                  });
                  Get.back();
                },
                child: Text(MyText.confirm.tr))
          ],
        ),
      );
    }),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void _initData() {
    MyHttpClient.initProject().then((value) {
      if (value.code == 200) {
        state.projectId = value.data!.id!;
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
    MyHttpClient.getAllCompanyUser().then((value) {
      if (value.code == 200) {
        state.listNumbers.value = value.data!;
        state.mapSelect
            .addEntries(state.listNumbers.map((e) => MapEntry(e, false)));
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
    });
  }

  void addConferenceResolutions() {
    _getLostData(true);
  }

  void addProjectPlanningPaper() {
    _getLostData(false);
  }

  Future<void> _getLostData(bool isConference) async {
    picker.FilePickerResult? result =
        await picker.FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: picker.FileType.custom,
      allowedExtensions: ['docx', 'pdf', 'doc', 'ppt', 'pptx', 'txt', 'md'],
    );

    if (result != null) {
      isConference
          ? state.listConferenceFiles.value = result.files
          : state.listPlanningFiles.value = result.files;
      isConference
          ? state.listConferenceFiles.refresh()
          : state.listPlanningFiles.refresh();
    } else {
      Utils.toastError('File not found');
    }
  }

  void submit() {
    if (state.projectName.value.isEmpty) {
      Utils.toastWarning(
          MyText.xCantBeNull.trParams({'x': MyText.projectName.tr}));
      return;
    }
    if (state.estimatedCost.value.isEmpty) {
      Utils.toastWarning(
          MyText.xCantBeNull.trParams({'x': MyText.estimatedCost.tr}));
      return;
    }
    if (DateTime.parse(state.projectStartTime.value)
        .isAfter(DateTime.parse(state.projectEndTime.value))) {
      Utils.toastWarning(MyText.startTimeAfterEndTime.tr);
      return;
    }
    if (state.projectDescription.isEmpty) {
      Utils.toastWarning(
          MyText.xCantBeNull.trParams({'x': MyText.projectDescription.tr}));
      return;
    }
    if (state.listSelectNumbers.isEmpty) {
      Utils.toastWarning(MyText.xCantBeNull.trParams({'x': MyText.member.tr}));
      return;
    }
    if (state.chargeId.isEmpty) {
      Utils.toastWarning(MyText.xCantBeNull.trParams({'x': MyText.charge.tr}));
      return;
    }
    if (state.listPlanningFiles.isEmpty) {
      Utils.toastWarning(
          MyText.xCantBeNull.trParams({'x': MyText.projectPlanningPaper.tr}));
      return;
    }
    _realSubmit();
  }

  Future<void> _realSubmit() async {
    LoadingElement.loadingDialog(true);
    List<dio.MultipartFile> conferenceFiles = state.listConferenceFiles
        .map((e) => dio.MultipartFile.fromFileSync(e.path!, filename: e.name))
        .toList();
    List<dio.MultipartFile> planningFiles = state.listPlanningFiles
        .map((e) => dio.MultipartFile.fromFileSync(e.path!, filename: e.name))
        .toList();
    state.listProjectPlanningPaper.clear();
    state.listConferenceResolutions.clear();
    await MyHttpClient.uploadFiles(conferenceFiles).then((value) {
      if (value.code == 200) {
        state.listConferenceResolutions.value = value.data!
            .map((e) => ConferenceResolutions(filename: e.name, url: e.url))
            .toList();
      } else {
        Get.back();
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
      return;
    });
    await MyHttpClient.uploadFiles(planningFiles).then((value) {
      if (value.code == 200) {
        state.listProjectPlanningPaper.value = value.data!
            .map((e) => ProjectPlanningPaper(filename: e.name, url: e.url))
            .toList();
      } else {
        Get.back();
        Utils.toastError(value.msg);
        return;
      }
    }).onError((error, stackTrace) {
      Get.back();
      Utils.toastError(error);
      return;
    });
    if (state.listProjectPlanningPaper.isNotEmpty &&
        state.listConferenceResolutions.isNotEmpty) {
      var companyUserId =
          state.listSelectNumbers.map((element) => element.id!).toList();
      var params = SubmitProjectRequestParams(
          id: state.projectId,
          companyUserIds: companyUserId,
          name: state.projectName.value,
          beginTime: state.projectStartTime.value,
          endTime: state.projectEndTime.value,
          estimateCost: int.parse(state.estimatedCost.value),
          description: state.projectDescription.value,
          status: state.projectStatus.value,
          chargeId: int.parse(state.chargeId.value),
          conferenceResolutions: state.listConferenceResolutions,
          projectPlanningPaper: state.listProjectPlanningPaper);
      await MyHttpClient.submitProject(params).then((value) {
        if (value.code == 200) {
          Get.back();
          Get.back();
        } else {
          Utils.toastError(value.msg);
        }
      }).onError((error, stackTrace) {
        Get.back();
        Utils.toastError(error);
      });
    } else {
      Get.back();
      Utils.toastError(MyText.errSomeThing);
    }
  }
}
